<template>
  <div class="page-container">
    <el-card class="filter-card">
      <el-form :model="filterForm" label-width="80px" :inline="true">
        <el-form-item label="签约状态">
          <el-select v-model="filterForm.status" placeholder="请选择">
            <el-option label="待支付" value="0"></el-option>
            <el-option label="已签约" value="1"></el-option>
            <el-option label="已过期" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="签约机构">
          <el-select v-model="filterForm.institution" placeholder="请选择签约机构">
            <el-option label="机构A" value="inst-a"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="医生团队">
          <el-select v-model="filterForm.doctorTeam" placeholder="请选择医生团队">
            <el-option label="张物质二队" value="team-zhang"></el-option>
            <el-option label="李物质好评团队" value="team-li"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="服务包">
          <el-select v-model="filterForm.servicePackage" placeholder="请选择服务包">
            <el-option label="老年服务包" value="pkg-old"></el-option>
            <el-option label="儿童服务包" value="pkg-child"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>

        <el-form-item label="关键字">
          <el-input v-model="filterForm.keyword" placeholder="请输入关键字" class="keyword-input"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch"></el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <el-table :data="tableData" style="width: 100%" border>
        <el-table-column prop="recordId" label="编号" width="80" />
        <el-table-column prop="residentName" label="签约人姓名" width="120" />
        <el-table-column prop="idCard" label="身份证号码" width="180" />
        <el-table-column prop="phoneNum" label="手机号" width="150" />
        <el-table-column prop="recordType" label="签约类型" width="100" />

        <!-- 修改签约状态列，使用自定义模板显示具体状态文字 -->
        <el-table-column prop="status" label="签约状态" width="180">
          <template #default="scope">
            <el-tag
                :type="getStatusTagType(scope.row.status)"
                size="small"
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="teamName" label="签约医生团队" width="150" />
        <el-table-column prop="pakName" label="签约服务包" width="150" />

        <el-table-column label="操作" width="220" fixed="right" align="center">
          <template #default="scope">
            <el-button size="small" type="success" @click="checkDetail(scope.row)">查看详情</el-button>
            <el-button size="small" type="primary" @click="updateInfo(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteSignRecord(scope.row.recordId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          class="pagination-container"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          :page-sizes="[5, 10, 20, 50]"  layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-card>

    <!--    控制弹窗显示的逻辑-->
    <record-detail
        v-if="dialogVisible"
        :visible="dialogVisible"
        :details="details"
        @update:visible="dialogVisible = $event"
    />
    <record-edit-dialog
        v-if="editDialogVisible"
        :visible="editDialogVisible"
        :edit-data="editData"
        @update:visible="editDialogVisible = $event"
        @save="handleSaveRecord"
    />
  </div>
</template>

<script>
import { Search } from '@element-plus/icons-vue';
import { useUserStore } from "../../store/user.js";
// 弹窗组件路径
import RecordDetail from "../../components/RecordDetail.vue";
import RecordEditDialog from '../../components/EditRecord.vue';
import {deleteRecord, queryRecord} from "../../api/record.js";

export default {
  name: "ContractRecords",
  components: {
    Search,
    //注册弹窗组件
    RecordDetail,
    RecordEditDialog
  },
  computed: {
    userInfo() {
      return useUserStore().userInfo;
    }
  },
  data() {
    return {
      Search: Search,
      filterForm: {},
      tableData: [],
      // 控制弹窗的显示/隐藏
      dialogVisible: false,
      editDialogVisible: false,
      // 传递给弹窗的详情数据
      details: {},
      editData: {},
      currentPage: 1,
      pageSize: 5,
      total: 0,  // 改为0，从后端获取真实数据
      // 状态映射对象
      statusMap: {
        0: '待支付',
        1: '已签约',
        2: '已过期'
      }
    };
  },
  methods: {
    // 根据状态码获取状态文字
    getStatusText(status) {
      return this.statusMap[status] || '未知状态';
    },

    // 根据状态码获取标签类型（用于不同颜色显示）
    getStatusTagType(status) {
      const typeMap = {
        0: 'warning',  // 待支付 - 橙色
        1: 'success',  // 已签约 - 绿色
        2: 'danger'    // 已过期 - 红色
      };
      return typeMap[status] || 'info';
    },

    async deleteSignRecord(id) {
      console.log("正在删除签约记录:", id);
      let {data: data} = await deleteRecord(id)
      if(data.code === 200) {
        this.$message.success('删除成功！');
        await this.queryAll();
      }else {
        this.$message.error('删除失败！');
        await this.queryAll();
      }
    }
    // 点击查询按钮，这块用于模糊查询
    ,handleSearch() {
      this.currentPage = 1; // 每次搜索都应该从第一页开始
      this.queryAll();
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.currentPage = 1; // 切换每页数量时，重置到第一页
      this.queryAll();
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.queryAll();
    }, async queryAll() {
      let {data: response} = await queryRecord(this.currentPage, this.pageSize);
      // 增加对返回数据的校验
      console.log("查询结果:", response);
      if (response && response.data) {
        this.tableData = response.data.list;
        console.log("查询结果:", this.tableData);
        this.total = response.data.total; // 从后端API获取总记录数
        console.log("总记录数:", this.total);
      } else {
        // 如果API返回格式不符或无数据，清空表格并重置总数
        this.tableData = [];
        this.total = 0;
      }
    }
    , async checkDetail(row) {
      console.log("查看详情:", row);
      this.details = row;
      // 打开弹窗
      this.dialogVisible = true;
    },
    handleSaveRecord(updatedData) {
      console.log('成功接收到编辑后的数据:', updatedData);
      this.$message.success('存储成功！');

      this.queryAll();
    },
    updateInfo(row) {
      this.editData = row;
      this.editDialogVisible = true
    }
  },mounted() {
    this.queryAll()
  }
}
</script>

<style scoped>
.page-container {
  padding: 20px;
}
.filter-card {
  margin-bottom: 20px;
}
.el-form-item {
  margin-right: 15px;
}
.keyword-input {
  width: 220px;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>